package edu.sysu.cshare.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.struts2.ServletActionContext;
import org.hibernate.Session;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionSupport;

import edu.sysu.cshare.model.Course;
import edu.sysu.cshare.model.Group;
import edu.sysu.cshare.model.Homework;
import edu.sysu.cshare.model.SubmitInfo;
import edu.sysu.cshare.model.User;
import edu.sysu.cshare.service.CourseService;
import edu.sysu.cshare.service.HomeworkService;
import edu.sysu.cshare.service.SubmitInfoService;
import edu.sysu.cshare.service.UserService;

@Controller
@Scope("prototype")
public class HomeworkAction extends ActionSupport {

	private UserService userService;
	private CourseService courseService;
	private HomeworkService homeworkService;
	private SubmitInfoService submitInfoService;
	private User user;
	private String userId;
	private boolean showUnDone;
	private boolean showDone;
	private long homeworkId;
	private Map courses;
	private Homework homework;
	private String startDateStr;
	private String dueDateStr;
	private File submitFile;
	private String submitFileContentType;
	private String submitFileFileName;
	private long submitInfoId;
	private String submitMsg;
	private final int BUFFER_SIZE = 16 * 1024;

	@Resource
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	@Resource
	public void setCourseService(CourseService courseService) {
		this.courseService = courseService;
	}

	@Resource
	public void setHomeworkService(HomeworkService homeworkService) {
		this.homeworkService = homeworkService;
	}

	@Resource
	public void setSubmitInfoService(SubmitInfoService submitInfoService) {
		this.submitInfoService = submitInfoService;
	}

	public User getUser() {
		return user;
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

	public boolean getShowUnDone() {
		return showUnDone;
	}

	public void setShowUnDone(boolean showUnDone) {
		this.showUnDone = showUnDone;
	}

	public boolean getShowDone() {
		return showDone;
	}

	public void setShowDone(boolean showDone) {
		this.showDone = showDone;
	}

	public long getHomeworkId() {
		return homeworkId;
	}

	public void setHomeworkId(long homeworkId) {
		this.homeworkId = homeworkId;
	}

	public Map getCourses() {
		return courses;
	}

	public Homework getHomework() {
		return homework;
	}

	public void setHomework(Homework homework) {
		this.homework = homework;
	}

	public String getStartDateStr() {
		return startDateStr;
	}

	public void setStartDateStr(String startDateStr) {
		this.startDateStr = startDateStr;
	}

	public String getDueDateStr() {
		return dueDateStr;
	}

	public void setDueDateStr(String dueDateStr) {
		this.dueDateStr = dueDateStr;
	}

	public void setSubmitFile(File submitFile) {
		this.submitFile = submitFile;
	}

	public void setSubmitFileContentType(String submitFileContentType) {
		this.submitFileContentType = submitFileContentType;
	}

	public void setSubmitFileFileName(String submitFileFileName) {
		this.submitFileFileName = submitFileFileName;
	}

	public void setSubmitInfoId(long submitInfoId) {
		this.submitInfoId = submitInfoId;
	}

	public String getSubmitMsg() {
		return submitMsg;
	}

	public String viewHomework() {
		user = userService.get(userId);
		return SUCCESS;
	}

	public String viewDetails() {
		user = userService.get(userId);
		Iterator it = courseService.loadAll().iterator();
		courses = new HashMap();
		Course c = null;
		while (it.hasNext()) {
			c = (Course) it.next();
			courses.put(c.getId(), c.getName());
		}
		homework = homeworkService.get(homeworkId);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH点");
		startDateStr = sdf.format(homework.getStartDate().getTime());
		dueDateStr = sdf.format(homework.getDueDate().getTime());
		return INPUT;
	}

	public String submitHomework() {
		user = userService.get(userId);
		if ((user.getRole() & 1) != 0) {
			SubmitInfo submitInfo = submitInfoService.get(submitInfoId);
			homework = submitInfo.getHomework();
			System.out.println(homework.getDirPath());
			if (homework.getDirPath() == null
					|| homework.getDirPath().length() == 0) {
				submitInfo.setSubmitDate(Calendar.getInstance());
				submitInfoService.update(submitInfo);
			} else {
				if (homework
						.getExtRestrict()
						.toLowerCase()
						.indexOf(
								submitFileFileName.toLowerCase()
										.substring(
												submitFileFileName
														.lastIndexOf(".") + 1)) == -1) {
					submitMsg = "文件格式不符合要求";
					return SUCCESS;
				}
				if (homework.getMaxSize() != 0) {
					if (submitFile.length() / 1024 > homework.getMaxSize()) {
						submitMsg = "文件大小超过限制";
						return SUCCESS;
					}
				}
				String dir = ServletActionContext.getServletContext()
						.getRealPath(homework.getDirPath()) + "/";
				File f = new File(dir + submitFileFileName);
				submitInfo.setSavePath(dir + submitFileFileName);
				submitInfo.setSubmitDate(Calendar.getInstance());
				submitInfoService.update(submitInfo);
				try {
					InputStream in = null;
					OutputStream out = null;
					try {
						in = new BufferedInputStream(new FileInputStream(
								submitFile), BUFFER_SIZE);
						out = new BufferedOutputStream(new FileOutputStream(f),
								BUFFER_SIZE);
						byte[] buffer = new byte[BUFFER_SIZE];
						while (in.read(buffer) > 0)
							out.write(buffer);
					} finally {
						if (in != null)
							in.close();
						if (out != null)
							out.close();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				if (homework.getSubmitByGroup()) {
					Group g = null;
					for (Group gt : user.getGroups()) {
						if (gt.getCourse().equals(homework.getCourse())) {
							g = gt;
							break;
						}
					}
					for (User u : g.getMembers()) {
						if (!u.equals(user)) {
							SubmitInfo si = null;
							for (SubmitInfo sit : u.getSubmitInfos()) {
								if (sit.getUser().equals(u)) {
									si = sit;
									break;
								}
							}
							si.setSavePath(dir + submitFileFileName);
							si.setSubmitDate(Calendar.getInstance());
							submitInfoService.update(si);
						}
					}
				}
			}
		}
		submitMsg = "提交成功";
		return SUCCESS;
	}

	public String modifyHomework() {
		user = userService.get(userId);
		Homework h = homeworkService.get(homeworkId);
		h.setCourse(courseService.get(homework.getCourse().getId()));
		h.setDescrip(homework.getDescrip());
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH点");
			Calendar startDate = new GregorianCalendar();
			startDate.setTime(sdf.parse(startDateStr));
			h.setStartDate(startDate);
			Calendar dueDate = new GregorianCalendar();
			dueDate.setTime(sdf.parse(dueDateStr));
			h.setDueDate(dueDate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		h.setMaxSize(homework.getMaxSize());
		h.setExtRestrict(homework.getExtRestrict());
		h.setSubmitMethod(homework.getSubmitMethod());
		h.setSubmitByGroup(homework.getSubmitByGroup());
		h.setRemark(homework.getRemark());
		h.setDirPath(homework.getDirPath());
		homeworkService.update(h);
		return SUCCESS;
	}
}
